<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!---------------------------------------------------- 头部区域 -------------------------------------------->
        <div class="header">
          <el-row type="flex" justify="space-between">
            <span class="info">说明：目前支持学科和关键字条件筛选</span>
            <el-button class="el-icon-edit addbth" type="success" @click="addQuestions">新增试题</el-button>
          </el-row>
        </div>
        <!----------------------------------------------------- 表单区域-------------------------------------- -->
        <el-form class="form" :model="searchForm" label-width="80px" inline>
          <el-row type="flex" justify="space-between" align="right">
            <el-col :span="6">
              <el-form-item label="学科">
                <el-select placeholder="请选择" size="small" v-model="searchForm.subjectID">
                  <el-option
                    v-for="item in subLists"
                    :key="item.id"
                    :label="item.subjectName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select v-model="searchForm.catalogID" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in catalogList"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select v-model="searchForm.tags" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in tagsList"
                    :key="item.id"
                    :label="item.subjectName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键字">
                <div class="inputsize">
                  <el-input placeholder="根据题干搜索" v-model="searchForm.keyword" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <el-form-item label="试题类型">
                <el-select v-model="searchForm.questionType" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度">
                <el-select v-model="searchForm.difficulty" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in difList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向">
                <el-select v-model="searchForm.direction" placeholder="请选择" size="small">
                  <el-option v-for="item in directionList" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录入人">
                <el-select v-model="searchForm.creatorID" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in creatorList"
                    :key="item.id"
                    :label="item.username"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between" align="right">
            <el-col :span="6">
              <el-form-item label="题目备注">
                <div class="inputsize">
                  <el-input v-model="searchForm.remarks" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称">
                <div class="inputsize">
                  <el-input v-model="searchForm.shortName" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="city">
                <el-form-item label="城市">
                  <div class="cityselect">
                    <el-select v-model="searchForm.province" placeholder="请选择" class="sel1">
                      <el-option
                        v-for="item in provincesList"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                    <el-select v-model="searchForm.city" placeholder="请选择">
                      <el-option v-for="item in citysList" :key="item" :label="item" :value="item" />
                    </el-select>
                  </div>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="6">
              <el-form-item class="formbtn">
                <div class="btnsize">
                  <el-button @click="clear">清除</el-button>
                  <el-button type="primary" @click="search">搜索</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!----------------------------------------------------- 提示框 --------------------------------------------------->
        <el-alert type="info" show-icon :closable="false">
          <template #title>数据一共{{total}}条</template>
        </el-alert>
        <!-- ---------------------------------------------------表格区域 ---------------------------------------------->
        <div class="mytable">
          <el-table :data="tableList" style="width: 100%">
            <el-table-column prop="number" label="试题编号"></el-table-column>
            <el-table-column prop="subject" label="学科"></el-table-column>
            <el-table-column prop="catalog" label="目录"></el-table-column>
            <el-table-column prop="questionType" label="题型">
              <template #default="{ row }">{{ qType(row.questionType) }}</template>
            </el-table-column>
            <el-table-column label="题干">
              <template #default="{ row }">
                <div v-html="row.question"></div>
              </template>
            </el-table-column>
            <el-table-column label="录入时间" width="160%">
              <template #default="{ row }">{{ timeChange(row.addDate) }}</template>
            </el-table-column>
            <el-table-column label="难度" align="center">
              <template #default="{ row }">{{ difficult(row.difficulty) }}</template>
            </el-table-column>
            <el-table-column prop="creator" label="录入人"></el-table-column>
            <el-table-column label="操作" width="200px">
              <template #default="{ row }">
                <el-button
                  type="info"
                  icon="el-icon-view"
                  circle
                  @click="previewQuestions(row.id)"
                />
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="replaceQuestions(row.id)"
                />
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteQuestions(row.id)"
                />
                <el-button
                  type="success"
                  icon="el-icon-circle-check"
                  circle
                  @click="addNew({id: row.id, choiceState: 1})"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- ------------------------------------------------分页器 ------------------------------------------------->
        <div class="mypagination">
          <el-pagination
            layout="prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 20, 30]"
            :current-page="q.page"
            :page-size="q.pagesize"
            :total="total"
            :pager-count="5"
            background
          ></el-pagination>
        </div>
      </el-card>
      <!-- ---------------------------------------------------预览题目弹框 --------------------------------------------->
      <el-dialog
        title="题目预览"
        :visible="showDialog"
        width="60%"
        @open="openDialog"
        @close="closeDialog"
      >
        <!-- 默认插槽 -->
        <template #default>
          <el-row>
            <el-col :span="6">
              <span>【题型】：{{qtype}}</span>
            </el-col>
            <el-col :span="6">
              <span>【编号】：{{detailList.id}}</span>
            </el-col>
            <el-col :span="6">
              <span>【难度】：{{diff}}</span>
            </el-col>
            <el-col :span="6">
              <span>【标签】：{{detailList.tags}}</span>
            </el-col>
            <el-col :span="6">
              <span>【学科】：{{detailList.subjectName}}</span>
            </el-col>
            <el-col :span="6">
              <span>【目录】：{{detailList.directoryName}}</span>
            </el-col>
            <el-col :span="6">
              <span>【方向】：{{detailList.direction}}</span>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <div>
            <p>【题干】：</p>
            <p v-html="detailList.question" style="color:blue"></p>
            <!-- 动态组件 -->
            <component
              :is="showVue"
              :List="detailList.options"
              :radioChoose="radioChoose"
              :checkboxChoose="checkboxChoose"
            />
          </div>
          <el-divider></el-divider>
          <div>
            <span>
              【参考答案】：
              <el-button type="danger" @click="openVideo">视频预览</el-button>
              <div class="demo" v-if="flag">
                <video ref="myvideo" width="320" height="240" type="video/mp4" poster controls></video>
              </div>
            </span>
          </div>
          <el-divider></el-divider>
          <div>
            <span>【答案解析】：</span>
            <span v-html="detailList.answer"></span>
          </div>
          <el-divider></el-divider>
          <div>
            <span>【题目备注】：{{detailList.remarks}}</span>
          </div>
        </template>
        <!-- 具名插槽 -->
        <template #footer>
          <el-button @click="close">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入接口
import { list as subList } from "@/api/hmmm/subjects.js";
import { simple as creatorsimple } from "@/api/base/users.js";
import { list as catalogList } from "@/api/hmmm/directorys.js";
import { list as tagsList } from "@/api/hmmm/tags.js";
import { provinces, citys } from "@/api/hmmm/citys.js";
import { list, detail, remove, choiceAdd } from "@/api/hmmm/questions.js";
import { direction, difficulty, questionType } from "@/api/hmmm/constants.js";
// 引入动态组件
import Radio from "@/module-hmmm/components/qP/Radio.vue";
import Checkbox from "@/module-hmmm/components/qP/Checkbox.vue";
// 引入dayjs包
var dayjs = require("dayjs");

// 引入测试MP4
// import videoCs from '@/assets/ce2.webm'

export default {
  name: "questionsIndex",
  components: {
    Radio,
    Checkbox
  },
  data() {
    return {
      // ----------------------------------------------------------表单数据---------------------------------------
      // 页码参数
      q: {
        page: 1,
        pagesize: 5
      },
      // 表单项数据
      searchForm: {
        subjectID: null,
        difficulty: "",
        questionType: "",
        tags: "",
        province: "",
        city: "",
        keyword: "",
        remarks: "",
        shortName: "",
        direction: "",
        creatorID: "",
        catalogID: ""
      },
      // 学科列表
      subLists: [],
      // 二级目录列表
      catalogList: [],
      // 标签列表
      tagsList: [],
      // 录入人列表
      creatorList: [],
      // 方向列表
      directionList: direction,
      // 难度列表
      difList: difficulty,
      // 试题类型列表
      typeList: questionType,
      // 省份列表
      provincesList: [],
      // 城市列表
      citysList: [],
      // -----------------------------------------------------------------表格数据--------------------------------------
      tableList: [],
      // ------------------------------------------------------------------分页器---------------------------------------------
      total: 0,
      // -----------------------------------------------------------------预览弹框-----------------------------------------
      showDialog: false,
      // 详情列表
      detailList: {},
      // 动态组件显示变量
      showVue: "",
      // 单选答案
      radioChoose: null,
      // 多选题的答案
      checkboxChoose: [],
      // 控制视频播放组件显隐
      flag: false,
      // 转换数据：题型(此处报错，已经修改函数名)
      qtype: "",
      // 转换数据：难度
      diff: ""
    };
  },
  created() {
    // 获取学科列表
    this.getsubsimple();
    // 获取录入人列表
    this.getcreatorList();
    // 获取省份
    this.getprovinces();
    // 获取表格数据
    this.gettableList();
  },
  computed: {
    // 简化学科属性，方便监听
    subjectID() {
      return this.searchForm.subjectID;
    },
    // 简化城市属性，方便监听
    province() {
      return this.searchForm.province;
    }
  },
  watch: {
    // 监听学科变化
    subjectID() {
      // 先清空二级目录和标签
      this.searchForm.tags = "";
      this.searchForm.catalogID = "";
      //获取二级目录列表
      this.getcatalogList();
      //获取标签列表
      this.gettagsList();
    },
    // 监听城市变化
    province() {
      this.searchForm.city = "";
      // 请求接口并传参，获取城市列表
      const res = citys(this.province);
      this.citysList = res;
    },
    //监听详情列表中题型的变化,
    "detailList.questionType"() {
      this.qtypeShow();
    },
    //监听详情列表中难度的变化,
    "detailList.difficulty"() {
      this.diffShow();
    }
  },
  methods: {
    // ---------------------------------------------------------------头部-------------------------------------------------
    // 新增按钮
    addQuestions() {
      // 跳转到试题录入模块
      this.$router.push({
        path: "/questions/new"
      });
    },
    // ---------------------------------------------------------------表单项--------------------------------------
    // 获取学科列表
    async getsubsimple() {
      const { data } = await subList();
      // console.log(data)
      this.subLists = data.items;
    },
    // 获取二级目录列表
    async getcatalogList() {
      const { data } = await catalogList({
        subjectID: this.searchForm.subjectID
      });
      // console.log(data)
      this.catalogList = data.items;
    },
    // 获取标签列表
    async gettagsList() {
      const { data } = await tagsList({ subjectID: this.searchForm.subjectID });
      console.log(data);
      this.tagsList = data.items;
    },
    // 获取用户列表
    async getcreatorList() {
      const res = await creatorsimple();
      // console.log(res)
      this.creatorList = res.data;
    },
    // 获取省份
    getprovinces() {
      const res = provinces();
      // console.log(res)
      this.provincesList = res;
    },
    // 获取方向列表
    // 搜索
    async search() {
      // 还原页码参数
      this.q = {
        page: 1,
        pagesize: 5
      };
      // 获取总参数（只支持关键字和学科搜索）
      const a = {
        ...this.q,
        subjectID: this.searchForm.subjectID,
        keyword: this.searchForm.keyword
      };
      // 请求接口，获取表格列表
      const { data } = await list(a);
      // console.log(data)
      this.tableList = data.items;
      this.total = data.counts;
    },
    // 清除
    clear() {
      // 还原页码参数
      this.q = {
        page: 1,
        pagesize: 5
      };
      // 还原表单项数据
      this.searchForm = {
        subjectID: null,
        difficulty: "",
        questionType: "",
        tags: "",
        province: "",
        city: "",
        keyword: "",
        remarks: "",
        shortName: "",
        direction: "",
        creatorID: "",
        catalogID: ""
      };
      // 请求接口，获取表格列表
      this.gettableList();
    },
    // ---------------------------------------------------------------表格区域---------------------------------
    // 请求表格列表
    async gettableList() {
      const res = await list(this.q);
      // console.log(res)
      this.tableList = res.data.items;
      this.total = res.data.counts;
    },
    // 题型处理函数
    qType(a) {
      const map = {
        1: "单选",
        2: "多选",
        3: "简答"
      };
      return map[a];
    },
    // 难点处理函数
    difficult(a) {
      const map = {
        1: "简单",
        2: "一般",
        3: "困难"
      };
      return map[a];
    },
    // 时间处理函数
    timeChange(a) {
      return dayjs(a).format("YYYY-MM-DD HH:mm:ss");
    },
    // 修改题目
    replaceQuestions(id) {
      // 跳转页面并携带参数
      this.$router.push({
        path: "/questions/new",
        query: {
          id
        }
      });
    },
    // 预览题目
    async previewQuestions(id) {
      this.showDialog = true;
      // 请求接口
      const res = await detail({ id });
      // console.log(res)
      this.detailList = res.data;
      // 判断使用哪一个动态组件
      // 根据类型判断显示哪一个组件（**********）
      if (this.detailList.questionType == "1") {
        // -------------------显示单选框
        this.showVue = Radio;
        // 获取单选答案
        const arr1 = this.detailList.options;
        // console.log(arr1);
        const index = arr1.findIndex(item => {
          return item.isRight === 1;
        });
        // console.log(index)
        // console.log(arr1[index].id);
        // 判断是否有选项
        if (index === -1) {
          this.radioChoose = null;
        } else {
          this.radioChoose = arr1[index].id;
        }
      } else if (this.detailList.questionType == "2") {
        // -----------------------显示多选框
        this.showVue = Checkbox;
        // 获取多选答案
        const arr = this.detailList.options;
        // console.log(arr);
        const filter2 = arr
          .filter(item => {
            return item.isRight === 1;
          })
          .map(item => {
            return item.id;
          });
        // console.log(filter2);
        // 判断是否有选项
        if (filter2.length === 0) {
          this.checkboxChoose = [];
        } else {
          this.checkboxChoose = filter2;
        }
      } else {
        this.showVue = "";
      }
    },
    // 删除题目
    deleteQuestions(id) {
      // 弹窗询问
      this.$confirm("此操作将永久删除题目，是否继续？", {
        type: "warning"
      })
        .then(async () => {
          // this.params.page = 1-----------------------(整理)
          const res = await remove({ id });
          // console.log(res);
          if (res.data.success === true) {
            // 提示成功
            this.$message.success("删除员工成功");
            // 优化页数和页面条数关系,避免出现删除后，页码没有数据
            if (this.tableList.length === 1 && this.q.page > 1) {
              this.q.page--;
            }
            // 刷新列表
            this.gettableList();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 加入精选题库
    addNew({ id, choiceState }) {
      // 弹窗询问
      this.$confirm("此操作将题目加入精选题库，是否继续？", {
        type: "info"
      })
        .then(async () => {
          // 请求接口
          const res = await choiceAdd({ id, choiceState });
          // console.log(res);
          if (res.data.success === true) {
            // 提示成功
            this.$message.success("添加成功");
            // 跳转到精选题库
            this.$router.push({
              path: "/questions/choice"
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // ----------------------------------------------------------------分页器 ---------------------------------------
    // 每页条数变化
    handleSizeChange(pagesize) {
      this.q.pagesize = pagesize;
      this.q.page = 1;
      // 重新获取表格列表
      this.gettableList();
    },
    // 页码变化
    handleCurrentChange(page) {
      this.q.page = page;
      // 重新获取表格列表
      this.gettableList();
    },
    // --------------------------------------------------------------预览弹框-----------------------------------------
    openDialog() {},
    closeDialog() {
      this.showDialog = false;
      // 还原详情列表
      this.detailList = {};
      // 还原单选答案
      this.radioChoose = null;
      // 还原多选答案
      this.checkboxChoose = [];
      // 关闭播放器
      this.flag = false;
    },
    // 关闭按钮
    close() {
      this.closeDialog();
    },
    //优化题型展示文字
    qtypeShow() {
      const a = this.detailList.questionType;
      // 修改文字形式
      if (a === "1" || a === "单选") {
        this.qtype = "单选";
      } else if (a === "2" || a === "多选") {
        this.qtype = "多选";
      } else if (a === "3" || a === "简答") {
        this.qtype = "简答";
      }
      // console.log(this.qtype)
    },
    //优化难度展示文字
    diffShow() {
      const a = this.detailList.difficulty;
      // 修改文字形式
      if (a === "1" || a === "简单") {
        this.diff = "简单";
      } else if (a === "2" || a === "一般") {
        this.diff = "一般";
      } else if (a === "3" || a === "困难") {
        this.diff = "困难";
      }
      // console.log(this.diff)
    },
    // 视频播放
    openVideo() {
      // 第二次点击关闭视频组件
      if (this.flag) {
        this.flag = false;
      } else {
        // 显示视频播放器
        this.flag = true;
        // console.log(this.detailList.videoURL);
        const url = this.detailList.videoURL;
        // 等dom元素加载完后修改属性
        this.$nextTick(() => {
          // 测试视频播放
          // this.$refs.myvideo.setAttribute('src', videoCs)
          this.$refs.myvideo.setAttribute("src", url);
          // console.log(this.$refs.myvideo.src);
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.header {
  height: 30px;
  .info {
    font-size: 14px;
    color: #ffc0cb;
  }
  // .addbth {
  //   width: 80px;
  //   height: 30px;
  //   text-align: center;
  //   line-height: 0;
  // }
}
.form {
  margin-top: 20px;
  .el-form-item {
    display: flex;
    .cityselect {
      display: flex;
      width: 75%;
    }
  }
  .formbtn {
    display: flex;
    justify-content: flex-end;
    .btnsize {
      margin-right: 15px;
    }
  }
}
.inputsize ::v-deep input {
  width: 100%;
  height: 30px;
}
// 样式穿透：修改双选框的样式
.cityselect ::v-deep input {
  width: 100px;
  height: 30px;
}
.btnsize ::v-deep button {
  height: 30px;
  font-size: 12px;
  text-align: center;
  // display: flex;
  span {
    // color: red;
  }
}
.mypagination {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
.demo {
  margin-top: 20px;
  width: 300px;
  height: 200px;
  // background-color: red;
}
</style>
